//全局变量存储文件对象
let videoFile = null;
let coverFile = null;
let isFormSubmitInitialized = false;
let isNavigationInitialized = false;
let isModalInitialized = false;

// 初始化文件上传区域
function initFileUploads() {
    // 创建并缓存文件输入元素
    const videoFileInput = document.getElementById('videoFileInput') || createFileInput('videoUpload');
    const coverFileInput = document.getElementById('coverFileInput') || createFileInput('coverUpload');
    
    // 获取上传区域
    const videoUpload = document.getElementById('videoUpload');
    const coverUpload = document.getElementById('coverUpload');
    
    // 防止重复绑定事件
    if (!videoUpload._initialized) {
        // 设置拖放功能
        setupDragDrop(videoUpload, videoFileInput, 'video');
        setupDragDrop(coverUpload, coverFileInput, 'image');
        
        // 设置点击功能
        videoUpload.addEventListener('click', () => videoFileInput.click());
        coverUpload.addEventListener('click', () => coverFileInput.click());
        
        // 监听文件选择变化
        videoFileInput.addEventListener('change', () => handleFileSelection(videoFileInput, videoUpload, 'video'));
        coverFileInput.addEventListener('change', () => handleFileSelection(coverFileInput, coverUpload, 'image'));
        
        // 标记为已初始化
        videoUpload._initialized = true;
        coverUpload._initialized = true;
    }
}

// 创建隐藏的文件输入元素
function createFileInput(id) {
    const input = document.createElement('input');
    input.type = 'file';
    input.id = `${id}Input`;
    input.style.display = 'none';
    input.accept = id === 'videoUpload' ? 'video/*' : 'image/*';
    document.body.appendChild(input);
    return input;
}

// 设置拖放功能
function setupDragDrop(uploadArea, fileInput, type) {
    uploadArea.addEventListener('dragover', function(e) {
        e.preventDefault();
        this.style.borderColor = '#00A1D6';
        this.style.backgroundColor = 'rgba(0, 161, 214, 0.1)';
    });

    uploadArea.addEventListener('dragleave', function() {
        this.style.borderColor = '';
        this.style.backgroundColor = '';
    });

    uploadArea.addEventListener('drop', function(e) {
        e.preventDefault();
        this.style.borderColor = '';
        this.style.backgroundColor = '';

        if (e.dataTransfer.files.length) {
            fileInput.files = e.dataTransfer.files;
            handleFileSelection(fileInput, uploadArea, type);
        }
    });
}

// 处理文件选择
function handleFileSelection(fileInput, uploadArea, type) {
    if (fileInput.files.length) {
        const file = fileInput.files[0];
        
        // 更新全局变量
        if (type === 'video') {
            videoFile = file;
        } else {
            coverFile = file;
        }
        
        // 更新UI显示
        uploadArea.innerHTML = `
            <i class="fas fa-check-circle" style="color:#4CAF50;"></i>
            <p>${file.name}</p>
            <p class="small" style="color:#4CAF50;">${type === 'video' ? '视频' : '封面'}已选择</p>
        `;
        
        // 重新绑定点击事件（因为innerHTML会移除原有的事件监听器）
        const fileInputEl = document.getElementById(`${uploadArea.id}Input`);
        uploadArea.addEventListener('click', () => fileInputEl.click());
    }
}

// 初始化表单提交（防止重复绑定）
function initFormSubmit() {
    if (isFormSubmitInitialized) return;
    
    // 使用命名空间管理事件
    $("#btn-submit").off('click.submitHandler').on('click.submitHandler', function(e) {
        console.log('提交按钮被点击');
        e.preventDefault();
        
        // 验证表单
        if (!videoFile) {
            alert('请选择视频文件');
            return;
        }
        
        const formData = new FormData();
        
        // 添加文本字段
        formData.append('videoTitle', $('#videoTitle').val());
        formData.append('videoDesc', $('#videoDesc').val());
        formData.append('videoCategory', $('#videoCategory').val());
        
        // 添加文件
        formData.append('videoFile', videoFile);
        if (coverFile) formData.append('coverFile', coverFile);
        
        // 发送Ajax请求
        $.ajax({
            type: "POST",
            url: "createCenter.do",
            data: formData,
            contentType: false,
            processData: false,
            beforeSend: function() {
                $("#btn-submit").html('<i class="fas fa-spinner fa-spin"></i> 上传中...').prop('disabled', true);
            },
            success: function(data) {
                console.log("上传成功:", data);
                alert('投稿成功！');
                uploadModal.style.display = 'none';
                document.body.style.overflow = 'auto';
                resetUploadForm();
            },
            error: function(xhr, status, error) {
                console.error("上传失败:", error);
                alert('投稿失败：' + (xhr.responseJSON ? xhr.responseJSON.message : '网络错误'));
            },
            complete: function() {
                $("#btn-submit").html('发布投稿').prop('disabled', false);
            }
        });
    });
    
    isFormSubmitInitialized = true;
}

// 重置上传表单
function resetUploadForm() {
    videoFile = null;
    coverFile = null;
    
    // 重置UI显示
    $('#videoUpload').html(`
        <i class="fas fa-cloud-upload-alt"></i>
        <p>点击或拖拽视频到此处</p>
        <p class="small">支持MP4、MOV、AVI等格式，最大2GB</p>
    `);
    
    $('#coverUpload').html(`
        <i class="fas fa-image"></i>
        <p>点击或拖拽封面到此处</p>
        <p class="small">支持JPG、PNG格式，建议尺寸1146x717</p>
    `);
    
    // 清空表单字段
    $('#videoTitle').val('');
    $('#videoDesc').val('');
    $('#videoCategory').val('');
}

// 初始化导航栏交互（防止重复绑定）
function initNavigation() {
    if (isNavigationInitialized) return;
    
    const navItems = document.querySelectorAll('.nav-item');
    navItems.forEach(item => {
        item.removeEventListener('click', handleNavClick);
        item.addEventListener('click', handleNavClick);
    });
    
    isNavigationInitialized = true;
}

// 导航栏点击处理函数
function handleNavClick(e) {
    const navItems = document.querySelectorAll('.nav-item');
    navItems.forEach(nav => nav.classList.remove('active'));
    this.classList.add('active');

    // 更新页面标题
    const title = this.querySelector('span').textContent;
    document.querySelector('.section-title').innerHTML =
        `<i class="${this.querySelector('i').className}"></i> ${title}`;
}

// 初始化模态框交互（防止重复绑定）
function initModal() {
    if (isModalInitialized) return;
    
    const uploadBtn = document.getElementById('uploadBtn');
    const uploadModal = document.getElementById('uploadModal');
    const closeBtn = document.querySelector('.close-btn');

    $(uploadBtn).off('click.modal').on('click.modal', function() {
        uploadModal.style.display = 'flex';
        document.body.style.overflow = 'hidden';
    });

    $(closeBtn).off('click.modal').on('click.modal', function() {
        uploadModal.style.display = 'none';
        document.body.style.overflow = 'auto';
    });

    $(window).off('click.modal').on('click.modal', function(event) {
        if (event.target === uploadModal) {
            uploadModal.style.display = 'none';
            document.body.style.overflow = 'auto';
        }
    });
    
    isModalInitialized = true;
}

// 页面加载完成后初始化所有功能
document.addEventListener('DOMContentLoaded', function() {
    console.log('DOMContentLoaded事件触发');
    initFileUploads();
    initFormSubmit();
    initNavigation();
    initModal();
});